<template>
  <div>
    <el-drawer
      :title="param.id ? $t('message.bjhyhx') : $t('message.xzhyhx')"
      :visible.sync="isShowModal"
      :before-close="handleClose"
      size="80%"
    >
      <div class="main_wrap">
        <div class="tag_set">
          <div class="property-title">{{ $t('message.hyhxdwwd') }}</div>
          <div class="placeholder9">{{ $t('message.drhxzd5') }}</div>
          <template v-for="(pt, i) in dimensionalityList">
            <div :key="pt.ptId">
              <div class="mt20 mb10 h2">{{ pt.ptName }}</div>
              <div class="tag_wrap">
                <div
                  v-for="(pd, t) in pt.pds"
                  :key="t"
                  class="tag"
                  :class="{ active: pd.selected }"
                  @click="tagClick(pd)"
                >
                  {{ pd.pdName }}
                </div>
              </div>
            </div>
          </template>
        </div>
        <div class="config">
          <div class="property-title">
            {{ param.id ? $t('message.bjhyhx') : $t('message.xzhyhx') }}
          </div>
          <el-form
            ref="form"
            class="doumee-form"
            :model="param"
            :rules="rules"
            label-width="auto"
            label-suffix="："
          >
            <el-form-item :label="$t('message.hyhx')" prop="name">
              <el-input
                v-model="param.name"
                maxlength="50"
                show-word-limit
                :placeholder="$t('message.qsrhxmc')"
              />
            </el-form-item>
            <el-form-item :label="$t('message.hxsm')">
              <el-input
                v-model="param.desc"
                :rows="5"
                :maxlength="80"
                type="textarea"
                :placeholder="$t('message.qsr')"
              />
            </el-form-item>
            <div class="h2 mb10">
              {{ $t('message.hytj') }}({{ selDateLength.length }}{{ $t('message.yx5') }})
            </div>
            <div class="placeholder9 fs12 mb20">
              {{ $t('message.cjrqmz') }}
            </div>
          </el-form>
          <div class="config_option">
            <template v-for="(pd, pdIndex) in selDataList">
              <div :key="pd.pdId" class="item">
                <i class="el-icon-close close" @click="selDataDel(pdIndex)" />
                <div class="line">
                  <div class="name">{{ pd.pdName }}</div>
                  <div class="placeholder9 fs12">{{ pd.pdDesc }}</div>
                </div>
                <template v-for="pdo in pd.pdos">
                  <div :key="pdo.pdoId" class="line option_wrap">
                    <div class="label">{{ pdo.pdoName }}：</div>
                    <div class="value">
                      <!-- 单选 -->
                      <div v-if="pdo.pdoType === '0'">
                        <el-radio
                          v-for="pdov in pdo.pdovs"
                          :key="pdov.pdovId"
                          v-model="pdo.pdovId"
                          :label="pdov.pdovId"
                          class="mb10"
                        >{{ pdov.pdovName }}</el-radio>
                      </div>
                      <!-- 多选 -->

                      <el-checkbox-group
                        v-if="pdo.pdoType === '1'"
                        v-model="pdo.valTemp"
                      >
                        <el-checkbox
                          v-for="pdov in pdo.options"
                          :key="pdov.id"
                          :label="pdov.id"
                          class="mb10"
                        >{{ pdov.name }}</el-checkbox>
                      </el-checkbox-group>
                      <!-- 输入框 -->
                      <div v-if="pdo.pdoType === '2'" class="">
                        <template v-for="(pdov, pdovi) in pdo.options">
                          <el-input
                            :key="pdovi"
                            v-model="pdov.val"
                            oninput="value=value.replace(/^(-1+)|[^\d]+/g, '').slice(0, 11)"
                            class="w100"
                          >
                            <span slot="append">{{
                              pdo.pdovs[0].pdovUnits
                            }}</span>
                          </el-input>
                          <span
                            v-if="pdovi < pdo.options.length - 1"
                            :key="pdovi"
                            class="ml10 mr10"
                          >~</span>
                        </template>
                      </div>
                      <!-- 标签 -->
                      <div v-if="pdo.pdoType === '3'">
                        <template v-for="(pdov, pdovii) in pdo.pdovs">
                          <el-radio-group
                            :key="pdovii"
                            v-model="pdo.pdovId"
                            class="mr10"
                            @input="(e) => changePdoTag(pdo, e)"
                          >
                            <el-radio-button
                              v-if="!pdov.pdovParentId"
                              :label="pdov.pdovId"
                            >{{ pdov.pdovName }}</el-radio-button>
                          </el-radio-group>
                        </template>
                        <el-date-picker
                          v-if="
                            pdo.pdovId === pdo.customId && pdo.pdovType === '4'
                          "
                          v-model="pdo.selDate"
                          type="daterange"
                          value-format="yyyy-MM-dd"
                          :range-separator="$t('message.zhi')"
                          :start-placeholder="$t('message.ksrq')"
                          :end-placeholder="$t('message.jsrq')"
                          class="w300"
                        />
                        <template>
                          <div
                            v-if="
                              pdo.pdovId === pdo.customId &&
                                pdo.pdovType === '5'
                            "
                            class="df_ac mt10"
                          >
                            <el-select
                              v-model="pdo.pdovIdSel"
                              style="width: 120px"
                              class="mr10"
                              @change="(e) => changePdov(pdo, e)"
                            >
                              <template v-for="pdov in pdo.pdovs">
                                <el-option
                                  v-if="pdov.pdovParentId"
                                  :key="pdov.pdovId"
                                  :label="pdov.pdovName"
                                  :value="pdov.pdovId"
                                />
                              </template>
                            </el-select>
                            <template v-for="(pdov, pdovii) in pdo.pdovs">
                              <el-date-picker
                                v-if="
                                  pdo.pdovId === pdo.customId &&
                                    pdov.pdovType === '4' &&
                                    pdo.pdovIdSel ==
                                    pdo.pdovs[pdo.pdovs.length - 1].pdovId
                                "
                                :key="pdovii"
                                v-model="pdo.selDate"
                                type="daterange"
                                value-format="yyyy-MM-dd"
                                :range-separator="$t('message.zhi')"
                                :start-placeholder="$t('message.ksrq')"
                                :end-placeholder="$t('message.jsrq')"
                                class="w300"
                              />
                            </template>
                            <div
                              v-for="(pdovIfn, pdovI) in pdo.options"
                              :key="pdovI"
                            >
                              <span v-if="pdovIfn.pdovUnitsBefore">{{
                                pdovIfn.pdovUnitsBefore
                              }}</span>
                              <el-input
                                v-model="pdovIfn.val"
                                oninput="value=value.replace(/^(-1+)|[^\d]+/g, '').slice(0, 11)"
                                class="w100"
                              >
                                <span slot="append">{{
                                  pdovIfn.pdovUnits
                                }}</span>
                              </el-input>
                              <span
                                v-if="pdovI < pdo.options.length - 1"
                                class="ml10 mr10"
                              >~</span>
                              <span v-if="pdovIfn.pdovUnitsAfter">{{
                                pdovIfn.pdovUnitsAfter
                              }}</span>
                            </div>
                          </div>
                        </template>
                      </div>
                    </div>
                  </div>
                </template>
              </div>
            </template>
          </div>
          <div>
            <el-button
              v-preventReClick
              :loading="subLoading"
              type="primary"
              @click="onSubmit"
            >{{ $t('message.baocun') }}</el-button>
            <el-button @click="handleClose">{{ $t('message.qx') }}</el-button>
          </div>
        </div>
      </div></el-drawer>
  </div>
</template>

<script>
import request from '@/utils/request'
import {
  portrayalPdPostList,
  portrayalPostAdd,
  portrayalPostEdit,
  portrayalPostDetail
} from '@/api'
import _ from 'lodash'
export default {
  data() {
    return {
      param: {},
      subLoading: false,
      dimensionalityList: [], // 维度列表
      selDataList: [],
      rules: {
        name: [{ required: true, message: this.$t('message.qsr') + this.$t('message.mc'), trigger: 'blur' }]
      },
      isShowModal: false,

      activepdId: '',
      pdIdEnable: false
    }
  },
  computed: {
    selDateLength() {
      const setList = [...new Set(this.selDataList.map(i => i.pdId))]
      return setList
    }
  },
  created() {
    // this.initData()
  },
  methods: {
    async tagClick(pd, val, pdovId, pdovIdSel) {
      // this.$nextTick(() => {
      //   this.pdIdEnable = false
      // })
      setTimeout(() => {
        this.pdIdEnable = false
      }, 500)
      if (this.pdIdEnable && this.activepdId === pd.pdId) {
        return
      }
      this.pdIdEnable = true
      this.activepdId = pd.pdId
      const { selDataList, dimensionalityList } = this
      const index = selDataList.findIndex(i => i.pdId === pd.pdId)
      if (index > -1) {
        this.selDataList.splice(index, 1)
      } else {
        if (selDataList.length === 5) {
          return this.$message.warning(this.$t('message.zdxz5'))
        }
        const obj = _.cloneDeep(pd)
        for (const pdo of obj.pdos) {
          // pdoType 0-单选，1-多选，2-输入框，3-tab标签
          if (pdo.pdoType === '1') { // 多选
            // pdo.pdovId = pdo.pdovs[0].pdovId
            const result = await this.requestApi(pdo.pdovs[0].interfaceNum)
            pdo.options = result.recordList.map(i => {
              return {
                name: i.name || i.cardName,
                id: String(i.id)
              }
            })
            pdo.valTemp = []
            if (val) {
              pdo.valTemp = val.split(',')
            }
          } else if (pdo.pdoType === '2') {
            // pdo.pdovId = pdo.pdovs[0].pdovId || ''
            pdo.options = []
            if (pdo.pdovs[0].pdovIfn > 0) {
              pdo.options.push({ val: '' })
              pdo.options.push({ val: '' })
              if (val) {
                pdo.options = []
                const arr = val.split(',')
                arr.forEach(aa => {
                  pdo.options.push({ val: aa })
                })
              }
            }
          } else if (pdo.pdoType === '3') {
            const customItem = pdo.pdovs.find(i => i.pdovName === this.$t('message.zdy'))
            if (customItem && customItem.pdovId) {
              pdo.customId = customItem.pdovId || ''
              pdo.pdovType = customItem.pdovType
            }
            pdo.options = []
            if (val) {
              pdo.selDate = val.split(',')
            }
            if (pdovId) {
              pdo.pdovId = pdovId
            }
            if (pdovIdSel) {
              pdo.pdovIdSel = pdovIdSel
            }
            setTimeout(() => {
              if (pdovIdSel) {
                pdo.pdovIdSel = pdovIdSel
                this.changePdov(pdo, pdovIdSel, val || '')
              }
            }, 500)
          } else if (pdo.pdoType === '0') {
            if (pdovId) {
              pdo.pdovId = pdovId
            }
          }
        }
        this.selDataList.push(obj)

        console.log('selDataList', this.selDataList)
      }

      dimensionalityList.forEach(item => {
        item.pds.forEach(item2 => {
          if (item2.pdId === pd.pdId) {
            item2.selected = !item2.selected
          }
        })
      })
    },
    changePdov(pdo, pdovId, val) {
      const { selDataList } = this
      const arr = _.cloneDeep(selDataList)
      arr.forEach(item => {
        if (item.pdId === pdo.pdId) {
          item.pdos.forEach(item2 => {
            const selItem = item2.pdovs.find(i => i.pdovId === pdovId)
            if (val) {
              const arrT = selItem.pdovIfnUnits.map((j, indexj) => {
                return {
                  pdovUnits: j.pdovUnits,
                  pdovUnitsAfter: j.pdovUnitsAfter || '',
                  pdovUnitsBefore: j.pdovUnitsBefore || '',
                  val: val.split(',')[indexj]
                }
              })
              item2.options = arrT
              return
            }
            // item2.val = ''
            item2.selDate = []
            item2.options = selItem.pdovIfnUnits
          })
        }
      })
      this.selDataList = arr
    },
    changePdoTag(pdo, pdovId) {
      const { selDataList } = this
      // const arr = _.cloneDeep(selDataList)

      // this.selDataList = arr
      // console.log(this.selDataList)
      // console.log(pdo)
      // console.log(pdovId)
    },
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const { selDataList, param } = this
          const arrTemp = []
          selDataList.forEach(item => {
            item.pdos.forEach(pdo => {
              if (pdo.selDate && pdo.selDate.length > 0) {
                pdo.val = pdo.selDate.join(',')
              }
              if (pdo.options && pdo.options.length > 0) {
                pdo.val = pdo.options.map(i => i.val).join(',')
              }
              if (pdo.valTemp && pdo.valTemp.length > 0) {
                pdo.val = pdo.valTemp.join(',')
              }
              if (pdo.pdovs && pdo.pdovs.length === 1) {
                pdo.pdovId = pdo.pdovs[0].pdovId
              }
              if (pdo.pdoType === '3' && pdo.customId !== pdo.pdovId) {
                // pdo.val = pdo.pdovId || ''
                if (pdo.val) {
                  pdo.val = pdo.val + ''
                }
                pdo.pdovIdSel = null
              }
              // pdo.pdovs = []
              arrTemp.push(pdo)
            })
          })
          for (const a in arrTemp) {
            if (arrTemp[a].pdoType === '3' && !arrTemp[a].pdovId) {
              return this.$message.warning(arrTemp[a].pdoName)
            }
            if (arrTemp[a].pdoType === '3' && arrTemp[a].val) {
              if (arrTemp[a].pdovIdSel) {
                const selItem = arrTemp[a].pdovs.find(i => i.pdovId == arrTemp[a].pdovIdSel)
                if (selItem.pdovType === '4') {
                  if (!arrTemp[a].selDate || arrTemp[a].selDate.length == 0) {
                    return this.$message.warning(arrTemp[a].pdoName)
                  }
                } else if (selItem.pdovType === '2') {
                  let count = 0
                  arrTemp[a].options.forEach(b => {
                    if (b.val) count++
                  })
                  if (count === 0) {
                    return this.$message.warning(arrTemp[a].pdoName)
                  }
                }
              }
            }
            if (arrTemp[a].val && arrTemp[a].val.indexOf(',') > -1) {
              if (arrTemp[a].pdoType === '1') {
                if (arrTemp[a].valTemp.length === 0) {
                  return this.$message.warning(arrTemp[a].pdoName)
                }
              } else if (arrTemp[a].pdoType === '3') {
                if (arrTemp[a].pdovIdSel) {
                  const selItem = arrTemp[a].pdovs.find(i => i.pdovId == arrTemp[a].pdovIdSel)
                  if (selItem.pdovType === '4') {
                    if (!arrTemp[a].selDate || arrTemp[a].selDate.length == 0) {
                      return this.$message.warning(arrTemp[a].pdoName)
                    }
                  } else if (selItem.pdovType === '2') {
                    let count = 0
                    arrTemp[a].options.forEach(b => {
                      if (b.val) count++
                    })
                    if (count === 0) {
                      return this.$message.warning(arrTemp[a].pdoName)
                    }
                  }
                }
              } else {
                let count = 0
                arrTemp[a].options.forEach(b => {
                  if (b.val) count++
                })
                if (count === 0) {
                  return this.$message.warning(arrTemp[a].pdoName)
                }
              }
            }
            if (!arrTemp[a].pdovId && !arrTemp[a].val) {
              return this.$message.warning(arrTemp[a].pdoName)
            }
          }
          // const arrtempSet = []
          // arrTemp.forEach(item => {
          //   const findIndex = arrtempSet.findIndex(i => i.pdId === item.pdId)
          //   if (findIndex === -1) {
          //     arrtempSet.push(item)
          //   } else {
          //     arrtempSet[findIndex].pdovId = item.pdovId
          //   }
          // })
          this.subLoading = true
          const fn = param.id ? portrayalPostEdit : portrayalPostAdd
          fn({
            param: {
              pdovrs: arrTemp,
              ...param
            }
          }).then(res => {
            this.subLoading = false
            this.handleClose()
            this.$message.success(this.$t('message.bccg'))
            this.$emit('success')
          }, () => {
            this.subLoading = false
          })
        }
      })
    },
    requestApi(code) {
      return request({
        url: '/do?c=' + code,
        method: 'post',
        data: { param: {}}
      })
    },
    selDataDel(index) {
      const pd = this.selDataList[index]
      this.selDataList.splice(index, 1)
      this.dimensionalityList.forEach(item => {
        item.pds.forEach(item2 => {
          if (item2.pdId === pd.pdId) {
            item2.selected = !item2.selected
          }
        })
      })
    },
    getDetail(id) {
      portrayalPostDetail({ param: { id }}).then(res => {
        const result = res.record
        this.$set(this.param, 'desc', result.desc || '')
        this.$set(this.param, 'name', result.name || '')
        this.$set(this.param, 'id', result.id || '')

        const tempRes = []
        result.pds.forEach((item, index) => {
          const activeIndex = tempRes.findIndex(i => i.pdId === item.pdId)
          if (activeIndex === -1) {
            tempRes.push(item)
          } else {
            if (item.val) {
              tempRes[activeIndex].val = item.val
            } else {
              tempRes[activeIndex].pdovId = item.pdovId
            }
          }
        })

        result.pds.forEach(item => {
          this.dimensionalityList.forEach(pt => {
            pt.pds.forEach(pd => {
              if (item.pdId === pd.pdId) {
                this.tagClick(pd, item.val || '', item.pdovId || '', item.pdovIdSel || '')
              }
            })
          })
        })
      })
    },
    initData(id) {
      portrayalPdPostList({ param: {}}).then(res => {
        this.dimensionalityList = res.recordList || []
        this.dimensionalityList.forEach(item => {
          item.pds.forEach(item2 => {
            item2.selected = false
          })
        })
        if (id) {
          this.getDetail(id)
        }
      })
    },
    handleClose() {
      this.isShowModal = false
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.main_wrap {
  margin: -20px;
  display: flex;
  .tag_set {
    padding: 20px;
    width: 360px;
    background-color: #f5f7fc;
    .tag_wrap {
      display: flex;
      flex-wrap: wrap;
      margin: 0 -5px;
      .tag {
        padding: 6px 16px;
        background: #ffffff;
        border-radius: 2px;
        border: 1px solid #dfe2e8;
        margin: 5px;
        min-width: 100px;
        text-align: center;
        cursor: pointer;
      }
      .active {
        color: $primaryColor;
        border: 1px solid $primaryColor;
      }
    }
  }
  .config {
    flex: 1;
    padding: 20px;
    .config_option {
      .item {
        position: relative;
        background-color: #f5f7fc;
        margin-bottom: 20px;
        padding: 16px;
        .line {
          display: flex;
          align-items: center;
          margin-bottom: 14px;
          &:last-child {
            margin-bottom: 0px;
          }
          .name {
            min-width: 80px;
            color: $primaryColor;
            font-weight: 700;
            font-size: 15px;
          }
          .label {
            min-width: 80px;
          }
        }
        .option_wrap {
          align-items: flex-start;
          ::v-deep .el-input-group__append {
            padding: 0 4px !important;
          }
        }
        .close {
          position: absolute;
          right: 4px;
          top: 4px;
          font-size: 18px;
          color: #979b9c;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
